#include <SFML/Graphics.hpp>
#include <cstdlib>
#include <cmath>
#include "ImgMap.h"

#define DISPLAY_WIDTH    800

ImgMap::~ImgMap()
{
    ImgMap::objit it;
    for (it = _objs.begin(); it != _objs.end(); ++it)
    {
        delete (*it);
        it = _objs.erase(it);
    }
}

void ImgMap::loadMap(std::string const & filename, std::vector<std::string> const & back)
{
    sf::Image * foreground = _mg.requireImage(filename);
    GameObject * obj;
    unsigned int row, col;
    std::vector<std::string>::const_iterator it;

    _size.set(foreground->GetWidth(), foreground->GetHeight());

    for (it = back.begin(); it != back.end(); ++it)
    {
        _objs.push_front(new GameObject(vector(), vector(), _size));
        _objs.front()->setGraphicComponent(*it);
    }

    for (row = 0; row < _size.y; row += IMap::CASE_SIZE)
    {

       for (col = 0; col < _size.x; col += IMap::CASE_SIZE)
        {
            // check first, last and middle pixels transparency
            // if all three are transparent, no block is added
            if (foreground->GetPixel(col, row).a != 0
                || foreground->GetPixel(col + IMap::CASE_SIZE / 2, row + IMap::CASE_SIZE / 2).a != 0
                || foreground->GetPixel(col + IMap::CASE_SIZE - 1, row + IMap::CASE_SIZE - 1).a != 0)
            {
                obj = new GameObject(vector(col, row),
                                     vector(0, 0),
                                     vector(IMap::CASE_SIZE, IMap::CASE_SIZE));
                obj->setGraphicComponent(filename, vector(col, row));
                insert_sorted(_objs, obj);
            }
        }
    }
}

vector ImgMap::getSize() { return _size; }

void ImgMap::collision(GameObject & obj, float const elapsedTime) const
{
    ImgMap::objlist::const_iterator it;

    for (it = _objs.begin(); it != _objs.end(); ++it)
        obj.checkCollision(*(*it), elapsedTime);
}

